<template>
  <div class="container">
    <header>
      <h1>{{ title }}</h1>
      <div class="header-controls">
        <div class="selection-mode">
          <button
            class="mode-btn"
            :class="{ active: selectionMode === 'single' }"
            @click="changeMode('single')"
          >单选模式</button>
          <button
            class="mode-btn"
            :class="{ active: selectionMode === 'multiple' }"
            @click="changeMode('multiple')"
          >多选模式</button>
        </div>
      </div>
    </header>

    <div class="content" style="flex:1;min-height:0;" :id="getHeight">
      <div class="sidebar">
        <div class="tree-container">
          <div class="tree-header">
            <i class="fas fa-sitemap"></i>
            <span>组织架构</span>
          </div>
          <!-- 将搜索框移到树形结构上方 -->
          <div class="tree-search">
            <div class="search-box">
              <i class="fas fa-search search-icon"></i>
              <el-input 
                clearable 
                type="text" 
                :placeholder="searchPlaceholder" 
                v-model="searchTerm"
                @input="handleTreeSearch"
              />
            </div>
          </div>
          <div class="tree-content">
            <el-tree
              ref="orgTree"
              :data="filteredOrgTree"
              :props="treeProps"
              :expand-on-click-node="false"
              :default-expand-all="false"
              node-key="label"
              @node-click="handleNodeClick"
            >
              <span class="custom-tree-node" slot-scope="{ node, data }">
                <i :class="getNodeIcon(node)"></i>
                <span class="node-label">{{ getNodeLabel(node) }}</span>
              </span>
            </el-tree>
          </div>
        </div>
      </div>

      <div class="main-content">
        <div class="users-header">
          <h2>{{ listTitle }}</h2>
          <div class="users-count">共找到 {{ filteredUsers.length }} 个用户</div>
        </div>

        <div class="users-grid">
          <div
            v-for="user in filteredUsers"
            :key="user.id"
            class="user-card"
            :class="{ 
              selected: isUserSelected(user.id),
              disabled: user.disabled
            }"
            @click="!user.disabled && toggleUser(user.id)"
          >
            <div class="checkbox-container">
              <div class="custom-checkbox"></div>
            </div>
            <div class="user-avatar">
              <div class="avatar-circle">
                {{ getAvatarText(user.memberName) }}
              </div>
            </div>
            <div class="user-info">
              <div class="user-name">{{ user.memberName }}</div>
              <div class="user-position">{{ user.position }}</div>
              <div class="user-phone">
                <i class="fas fa-phone"></i>
                {{ user.telephone }}
              </div>
              <div class="user-status">
                <div class="status-dot" :class="`status-${user.status || 'available'}`"></div>
                {{ getStatusText(user.status) }}
              </div>
            </div>
          </div>

          <div v-if="filteredUsers.length === 0" class="no-users">
            <i class="fas fa-users-slash no-users-icon"></i>
            <div class="no-users-text">{{ noDataText }}</div>
          </div>
        </div>
      </div>
    </div>

    <div class="footer">
      <div class="selected-info">
        已选择
        <span class="selected-count">{{ selectedUsers.length }}</span> 个用户
      </div>
      <div class="footer-buttons">
        <button class="cancel-btn" @click="handleCancel">取消</button>
        <button
          class="confirm-btn"
          :disabled="selectedUsers.length === 0"
          @click="confirmSelection"
        >{{ confirmButtonText }}</button>
      </div>
    </div>
  </div>
</template>

<script>
export default {
  name: "UserSelection",
  props: {
    // 基础配置
    title: {
      type: String,
      default: "选择用户"
    },
    listTitle: {
      type: String,
      default: "用户列表"
    },
    searchPlaceholder: {
      type: String,
      default: "搜索组织架构..."
    },
    confirmButtonText: {
      type: String,
      default: "确认选择"
    },
    noDataText: {
      type: String,
      default: "未找到符合条件的用户"
    },

    // 数据
    userList: {
      type: Array,
      default: () => [
        {
          memberName: '蒋海迪',
          telephone: '13860437507',
          position: '机修班长',
          id: 'USER-001',
          status: 'available'
        },
        {
          memberName: '张三',
          telephone: '13860437508',
          position: '机修工',
          id: 'USER-002',
          status: 'available'
        },
        {
          memberName: '李四',
          telephone: '13860437509',
          position: '运行工程师',
          id: 'USER-003',
          status: 'inuse',
          disabled: true
        },
        {
          memberName: '王五',
          telephone: '13860437510',
          position: '化验员',
          id: 'USER-004',
          status: 'available'
        }
      ],
    },

    // 初始值
    initialMode: {
      type: String,
      default: "single",
      validator: value => ["single", "multiple"].includes(value)
    },
    initialSelected: {
      type: Array,
      default: () => []
    },

    // 配置选项
    allowCancel: {
      type: Boolean,
      default: true
    },
    showStatus: {
      type: Boolean,
      default: true
    }
  },
  data() {
    return {
      selectionMode: this.initialMode,
      selectedCategory: "all",
      searchTerm: "",
      selectedUsers: [...this.initialSelected],
      currentDepartment: null,
      treeProps: {
        children: "children",
        label: "label"
      },
      orgTree: [
        {
          label: "厦门市政",
          type: "company",
          children: [
            {
              label: "翔安水厂",
              type: "company",
              children: [
                {
                  label: "综合室",
                  type: "department",
                  children: [{ label: "未知", type: "unknown" }]
                },
                {
                  label: "生产室",
                  type: "department",
                  children: [{ label: "未知", type: "unknown" }]
                },
                {
                  label: "化验室",
                  type: "department",
                  children: [{ label: "未知", type: "unknown" }]
                },
                {
                  label: "运行班组",
                  type: "department",
                  children: [{ label: "未知", type: "unknown" }]
                },
                {
                  label: "机修班组",
                  type: "department",
                  children: [
                    { label: "测试岗位", type: "position" },
                    { label: "机修班长", type: "position" },
                    { label: "机修副班长", type: "position" },
                    { label: "机修工", type: "position" }
                  ]
                },
                { label: "厂长", type: "position" },
                { label: "副厂长", type: "position" },
                { label: "安保", type: "department" }
              ]
            },
            {
              label: "新圩水厂",
              type: "company",
              children: [{ label: "未知", type: "unknown" }]
            }
          ]
        }
      ]
    };
  },
  computed: {
    filteredUsers() {
      let filtered = this.userList;

      // 按部门筛选
      if (this.currentDepartment) {
        filtered = filtered.filter(user => 
          user.position.includes(this.currentDepartment) || 
          user.position === this.currentDepartment
        );
      }

      return filtered;
    },
    
    // 过滤组织架构树
    filteredOrgTree() {
      if (!this.searchTerm) {
        return this.orgTree;
      }
      
      const filterTree = (nodes) => {
        return nodes.filter(node => {
          const matches = node.label.toLowerCase().includes(this.searchTerm.toLowerCase());
          if (node.children) {
            const filteredChildren = filterTree(node.children);
            if (filteredChildren.length > 0) {
              node.children = filteredChildren;
              return true;
            }
          }
          return matches;
        });
      };
      
      return filterTree(JSON.parse(JSON.stringify(this.orgTree)));
    },
    
    getHeight() {
      let upDownH = 0;
      this.$nextTick(() => {
        let head_h = document.getElementsByTagName("header");
        let foot_h = document.getElementsByClassName("footer");
        if (head_h) {
          upDownH = head_h[0].offsetHeight;
        }
        if (foot_h) {
          upDownH += foot_h[0].offsetHeight;
        }
        let content = document.querySelector(".content");
        if (content) {
          content.style.height = `calc(80vh - ${upDownH}px)`;
        }
      });
      return upDownH;
    }
  },
  watch: {
    initialSelected(newVal) {
      this.selectedUsers = [...newVal];
    },
    initialMode(newVal) {
      this.selectionMode = newVal;
    }
  },

  methods: {
    getNodeIcon(node) {
      const icons = {
        company: "fas fa-building",
        department: "fas fa-users",
        position: "fas fa-user-tie",
        unknown: "fas fa-question-circle"
      };

      return icons[node.data.type] || "fas fa-folder";
    },

    getNodeLabel(node) {
      return node.label;
    },

    getAvatarText(name) {
      return name ? name.charAt(0) : '?';
    },

    handleTreeSearch() {
      // 搜索组织架构时自动展开匹配的节点
      if (this.searchTerm) {
        this.$nextTick(() => {
          const tree = this.$refs.orgTree;
          if (tree) {
            tree.store._getAllNodes().forEach(node => {
              if (node.expanded) {
                node.collapse();
              }
            });
            // 展开所有节点以显示搜索结果
            tree.store._getAllNodes().forEach(node => {
              node.expand();
            });
          }
        });
      }
    },

    handleNodeClick(data, node) {
      console.log("节点点击:", data, node);
      // 根据点击的节点筛选用户
      if (data.type === "department" || data.type === "position") {
        this.currentDepartment = data.label;
      } else {
        this.currentDepartment = null;
      }
    },

    changeMode(mode) {
      this.selectionMode = mode;

      // 如果是单选模式且当前选择了多个用户，只保留第一个
      if (mode === "single" && this.selectedUsers.length > 1) {
        this.selectedUsers = [this.selectedUsers[0]];
      }

      this.$emit("mode-change", mode);
    },

    isUserSelected(userId) {
      return this.selectedUsers.includes(userId);
    },

    toggleUser(userId) {
      const user = this.userList.find(u => u.id === userId);
      if (user && user.disabled) return;

      if (this.selectionMode === "single") {
        // 单选模式：直接替换选中用户
        this.selectedUsers = [userId];
      } else {
        // 多选模式：切换选中状态
        const index = this.selectedUsers.indexOf(userId);
        if (index > -1) {
          this.selectedUsers.splice(index, 1);
        } else {
          this.selectedUsers.push(userId);
        }
      }

      this.$emit("selection-change", this.selectedUsers);
    },

    getStatusText(status) {
      const statusMap = {
        available: "在线",
        inuse: "忙碌",
        maintenance: "离线"
      };
      return statusMap[status] || "在线";
    },

    confirmSelection() {
      if (this.selectedUsers.length === 0) return;

      const selectedUsersData = this.userList.filter(user =>
        this.selectedUsers.includes(user.id)
      );

      this.$emit("confirm", {
        userIds: this.selectedUsers,
        users: selectedUsersData,
        mode: this.selectionMode
      });
    },

    handleCancel() {
      this.$emit("cancel");
    },

    // 公共方法：清除选择
    clearSelection() {
      this.selectedUsers = [];
      this.$emit("selection-change", this.selectedUsers);
    },

    // 公共方法：设置选择
    setSelection(userIds) {
      if (this.selectionMode === "single" && userIds.length > 1) {
        console.warn("单选模式下只能选择一个用户，将使用第一个用户ID");
        this.selectedUsers = [userIds[0]];
      } else {
        this.selectedUsers = [...userIds];
      }
      this.$emit("selection-change", this.selectedUsers);
    }
  }
};
</script>

<style scoped>
/* 保持原有的基础样式不变 */
* {
  margin: 0;
  padding: 0;
  box-sizing: border-box;
  font-family: "Segoe UI", "Microsoft YaHei", sans-serif;
}

.container {
  max-height: 80vh;
  width: 70%;
  max-width: 1000px;
  background: white;
  border-radius: 12px;
  box-shadow: 0 5px 20px rgba(0, 0, 0, 0.08);
  overflow: hidden;
}

header {
  padding: 24px 30px;
  border-bottom: 1px solid #eaeef2;
  display: flex;
  justify-content: space-between;
  align-items: center;
  background: linear-gradient(135deg, #095b90, #6a82fb);
  color: white;
}

h1 {
  font-size: 24px;
  font-weight: 600;
}

.header-controls {
  display: flex;
  align-items: center;
  gap: 20px;
}

.selection-mode {
  display: flex;
  align-items: center;
  background: rgba(255, 255, 255, 0.2);
  border-radius: 6px;
  padding: 5px;
}

.mode-btn {
  padding: 8px 16px;
  border: none;
  background: transparent;
  color: white;
  border-radius: 4px;
  cursor: pointer;
  font-size: 14px;
  transition: all 0.2s;
}

.mode-btn.active {
  background: rgba(255, 255, 255, 0.3);
  font-weight: 500;
}

.content {
  display: flex;
  min-height: 500px;
  box-sizing: border-box;
}

.sidebar {
  width: 260px;
  background: #f8fafc;
  border-right: 1px solid #eaeef2;
  padding: 0;
  overflow-y: auto;
}

.tree-container {
  height: 100%;
  display: flex;
  flex-direction: column;
}

.tree-header {
  padding: 18px 20px;
  background: #edf2ff;
  border-bottom: 1px solid #e1e8f0;
  display: flex;
  align-items: center;
  font-weight: 600;
  color: #4a5568;
}

.tree-header i {
  margin-right: 10px;
  color: #6a82fb;
}

/* 树形结构搜索框样式 */
.tree-search {
  padding: 15px 20px;
  border-bottom: 1px solid #eaeef2;
  background: #f8fafc;
}

.tree-search .search-box {
  position: relative;
  width: 100%;
}

.tree-search .search-box el-input {
  width: 100%;
  padding: 10px 15px 10px 40px;
  border: 1px solid #e1e8f0;
  border-radius: 20px;
  background: white;
  font-size: 14px;
  transition: all 0.3s;
}

.tree-search .search-box el-input:focus {
  outline: none;
  box-shadow: 0 0 0 2px rgba(106, 130, 251, 0.2);
  border-color: #6a82fb;
}

.tree-search .search-icon {
  position: absolute;
  left: 15px;
  top: 50%;
  transform: translateY(-50%);
  color: #6a82fb;
  z-index: 1;
}

.tree-content {
  flex: 1;
  padding: 15px 0;
  overflow-y: auto;
}

/* 树形结构样式优化 */
::v-deep .el-tree {
  background: transparent;
  font-size: 14px;
}

::v-deep .el-tree-node__content {
  height: 38px;
  padding: 0 15px;
  transition: all 0.2s;
  border-left: 3px solid transparent;
}

::v-deep .el-tree-node__content:hover {
  background-color: #f0f5ff;
  border-left-color: #6a82fb;
}

::v-deep .el-tree-node:focus > .el-tree-node__content {
  background-color: #e8eeff;
}

::v-deep .el-tree-node.is-current > .el-tree-node__content {
  background-color: #e8eeff;
  border-left-color: #6a82fb;
  font-weight: 500;
}

.custom-tree-node {
  display: flex;
  align-items: center;
  width: 100%;
}

.custom-tree-node i {
  margin-right: 8px;
  font-size: 14px;
  width: 16px;
  text-align: center;
}

.node-label {
  flex: 1;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

/* 不同节点类型的图标颜色 */
::v-deep .fa-building {
  color: #4c6ef5;
}

::v-deep .fa-users {
  color: #40c057;
}

::v-deep .fa-user-tie {
  color: #fab005;
}

::v-deep .fa-question-circle {
  color: #868e96;
}

::v-deep .fa-folder {
  color: #fab005;
}

/* 树形结构展开/收起图标样式 */
::v-deep .el-tree-node:not(.is-leaf) .el-tree-node__expand-icon:not(.is-leaf){
  color: #6a82fb;
  font-size: 14px;
  transition: transform 0.2s;
}

::v-deep .el-tree-node:not(.is-leaf) .el-tree-node__expand-icon.expanded {
  transform: rotate(90deg);
}

::v-deep .el-tree-node.is-leaf .el-tree-node__expand-icon {
  visibility: hidden;
}

/* 用户列表样式设计 */
.main-content {
  flex: 1;
  padding: 25px 30px;
  overflow-y: auto;
}

.users-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 25px;
}

.users-header h2 {
  font-size: 20px;
  font-weight: 600;
  color: #333;
}

.users-count {
  color: #666;
  font-size: 14px;
}

.users-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(280px, 1fr));
  gap: 16px;
}

.user-card {
  background: white;
  border-radius: 12px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.06);
  padding: 20px;
  transition: all 0.3s ease;
  border: 2px solid transparent;
  position: relative;
  display: flex;
  align-items: flex-start;
  gap: 16px;
  cursor: pointer;
}

.user-card:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.1);
  border-color: #eaeef2;
}

.user-card.selected {
  border-color: #6a82fb;
  background: linear-gradient(135deg, #f8faff, #f0f5ff);
  box-shadow: 0 4px 16px rgba(106, 130, 251, 0.15);
}

.user-card.disabled {
  opacity: 0.5;
  cursor: not-allowed;
}

.user-card.disabled:hover {
  transform: none;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.06);
  border-color: transparent;
}

.checkbox-container {
  position: absolute;
  top: 16px;
  right: 16px;
}

.custom-checkbox {
  width: 20px;
  height: 20px;
  border: 2px solid #ddd;
  border-radius: 4px;
  display: flex;
  align-items: center;
  justify-content: center;
  transition: all 0.2s;
  background: white;
}

.user-card.selected .custom-checkbox {
  background: #6a82fb;
  border-color: #6a82fb;
}

.user-card.disabled .custom-checkbox {
  border-color: #ccc;
  background: #f5f5f5;
}

.custom-checkbox::after {
  content: "";
  width: 5px;
  height: 10px;
  border: solid white;
  border-width: 0 2px 2px 0;
  transform: rotate(45deg) scale(0);
  transition: all 0.2s;
}

.user-card.selected .custom-checkbox::after {
  transform: rotate(45deg) scale(1);
}

.user-avatar {
  flex-shrink: 0;
}

.avatar-circle {
  width: 60px;
  height: 60px;
  border-radius: 50%;
  background: linear-gradient(135deg, #6a82fb, #fc5c7d);
  display: flex;
  align-items: center;
  justify-content: center;
  color: white;
  font-size: 20px;
  font-weight: 600;
  box-shadow: 0 4px 12px rgba(106, 130, 251, 0.3);
}

.user-info {
  flex: 1;
  min-width: 0;
}

.user-name {
  font-size: 18px;
  font-weight: 600;
  color: #333;
  margin-bottom: 6px;
  line-height: 1.2;
}

.user-position {
  font-size: 14px;
  color: #6a82fb;
  font-weight: 500;
  margin-bottom: 8px;
  padding: 4px 8px;
  background: #edf2ff;
  border-radius: 6px;
  display: inline-block;
}

.user-phone {
  font-size: 13px;
  color: #666;
  margin-bottom: 8px;
  display: flex;
  align-items: center;
  gap: 6px;
}

.user-phone i {
  color: #6a82fb;
  font-size: 12px;
}

.user-status {
  display: flex;
  align-items: center;
  font-size: 12px;
  color: #888;
  gap: 6px;
}

.status-dot {
  width: 8px;
  height: 8px;
  border-radius: 50%;
  flex-shrink: 0;
}

.status-available {
  background: #4caf50;
  box-shadow: 0 0 6px rgba(76, 175, 80, 0.4);
}

.status-inuse {
  background: #ff9800;
  box-shadow: 0 0 6px rgba(255, 152, 0, 0.4);
}

.status-maintenance {
  background: #f44336;
  box-shadow: 0 0 6px rgba(244, 67, 54, 0.4);
}

.no-users {
  text-align: center;
  padding: 60px 40px;
  color: #888;
  grid-column: 1 / -1;
}

.no-users-icon {
  font-size: 48px;
  margin-bottom: 16px;
  color: #ccc;
}

.no-users-text {
  font-size: 16px;
  color: #999;
}

.footer {
  padding: 20px 30px;
  border-top: 1px solid #eaeef2;
  display: flex;
  justify-content: space-between;
  align-items: center;
  background: #f8fafc;
}

.selected-info {
  color: #666;
  font-size: 14px;
}

.selected-count {
  font-weight: 600;
  color: #6a82fb;
}

.footer-buttons {
  display: flex;
  gap: 12px;
}

.cancel-btn {
  background: #f8f9fa;
  color: #666;
  border: 1px solid #ddd;
  padding: 12px 24px;
  border-radius: 6px;
  cursor: pointer;
  font-size: 14px;
  font-weight: 500;
  transition: all 0.2s;
}

.cancel-btn:hover {
  background: #e9ecef;
  border-color: #adb5bd;
}

.confirm-btn {
  background: #6a82fb;
  color: white;
  border: none;
  padding: 12px 30px;
  border-radius: 6px;
  cursor: pointer;
  font-size: 15px;
  font-weight: 500;
  transition: all 0.2s;
}

.confirm-btn:hover:not(:disabled) {
  background: #5a72e5;
  box-shadow: 0 4px 10px rgba(106, 130, 251, 0.3);
}

.confirm-btn:disabled {
  background: #ccc;
  cursor: not-allowed;
  box-shadow: none;
}
</style>